package com.sinosoft.service.impl.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sinosoft.common.CommonConst;
import com.sinosoft.entity.DefUser;
import com.sinosoft.exception.ComplainException;
import com.sinosoft.mapper.DefUserMapper;
import com.sinosoft.service.system.IUserService;
import com.sinosoft.util.MD5Util;

@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	private DefUserMapper userMapper;
	
	@Override
	public Map<String, Object> selectUserByCondition(DefUser user) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<DefUser> userList = userMapper.selectByCondition(user);
		for (DefUser u : userList) {
			u.setRcState(CommonConst.RC_STATE.get(u.getRcState()));
		}
		resultMap.put("rows", userList);
		resultMap.put("total", userMapper.selectByConditionCount(user));
		return resultMap;
	}

	@Transactional
	@Override
	public Map<String, Object> addUser(DefUser user) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//新增用户时，密码默认为123456
		user.setPassword(MD5Util.md5("123456"));
		int n = userMapper.addUser(user);
		if (1 == n) {
			resultMap.put("flag", true);
			resultMap.put("msg", "添加成功！");
		} else {
			throw new ComplainException("添加用户失败！插入动作影响记录数不等于1条！");
		}
		return resultMap;
	}

	@Transactional
	@Override
	public Map<String, Object> modifyUser(DefUser user) {
		Map<String, Object> map = new HashMap<String, Object>();
		int n = userMapper.modifyUser(user);
		if (1 == n) {
			map.put("flag", true);
			map.put("msg", "修改成功！");
		} else {
			throw new ComplainException("修改用户失败！修改动作影响记录数不等于1条！");
		}
		return map;
	}

	@Transactional
	@Override
	public Map<String, Object> deleteUser(Integer userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		int n = userMapper.deleteUser(userId);
		if (n == 1) {
			map.put("flag", true);
			map.put("msg", "删除成功！");
		} else {
			throw new ComplainException("删除失败！删除动作影响记录数不等于1条！");
		}
		return map;
	}

}
